/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.homepage.calendar.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.StopWatch;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.message.vo.Notice;
import com.je.common.base.message.vo.NoticeMsg;
import com.je.common.base.message.vo.PushSystemMessage;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.common.base.util.TreeUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.message.Push;
import com.je.message.rpc.PlatformGeneralPushRpcService;
import com.je.message.rpc.PortalRpcService;
import com.je.message.rpc.SocketPushMessageRpcService;
import com.je.message.vo.Message;
import com.je.message.vo.WebPushTypeEnum;
import com.je.meta.service.homepage.calendar.CalendarService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CalendarServiceImpl implements CalendarService {

    private static Logger logger = LoggerFactory.getLogger(CalendarServiceImpl.class);

    @Autowired
    private MetaService metaService;
    @Qualifier("taskExecutor")
    @Autowired
    private TaskExecutor taskExecutor;
    @Autowired
    private PlatformGeneralPushRpcService platformGeneralPushRpcService;
    @Autowired
    private SocketPushMessageRpcService socketPushMessageRpcService;
    @Autowired
    private PortalRpcService portalRpcService;

    /**
     * 获取我的任务树形
     * @return
     */
    @Override
    public JSONTreeNode getMyTaskTree() {
        //最近两个月的数据
        Date nowDate = new Date();
        Integer year = nowDate.getYear() + 1900;
        Integer month = nowDate.getMonth() + 1;
        String start = DateUtils.formatDate(DateUtils.getDate(DateUtils.getFirstDayOfMonth(year, month - 1))) + " 00:00:00";
        String end = DateUtils.formatDate(DateUtils.getDate(DateUtils.getFirstDayOfMonth(year, month + 1))) + " 00:00:00";
        List<DynaBean> tasks = metaService.select("JE_SYS_CALENDAR", ConditionsWrapper.builder().apply(" AND SY_CREATEUSERID = '" + SecurityUserHolder.getCurrentAccountRealUserId() + "' AND CALENDAR_STARTTIME>='" + start + "'  AND CALENDAR_STARTTIME<'" + end + "' ORDER BY CALENDAR_STARTTIME DESC"));
        JSONTreeNode root = TreeUtil.buildRootNode();
        List<JSONTreeNode> lists = new ArrayList<JSONTreeNode>();
        for (DynaBean task : tasks) {
            JSONTreeNode taskNode = TreeUtil.buildTreeNode(task.getPkValue(), task.getStr("CALENDAR_TITLE"), "", task.getStr("CALENDAR_NOTES"), task.getStr("CALENDAR_CALENDARTYPE_CODE"), "jeicon jeicon-task", root.getId());
            if (!"-1".equals(task.getStr("CALENDAR_REMINDER_CODE"))) {
                Integer remind = task.getInt("CALENDAR_REMINDER_CODE");
                Date startTime = DateUtils.getDate(task.getStr("CALENDAR_STARTTIME"), DateUtils.DAFAULT_DATETIME_FORMAT);
                if (startTime == null) {
                    startTime = DateUtils.getDate(task.getStr("CALENDAR_STARTTIME"), DateUtils.DAFAULT_DATE_FORMAT);
                }
                Date endTime = DateUtils.getDate(task.getStr("CALENDAR_ENDTIME"), DateUtils.DAFAULT_DATETIME_FORMAT);
                if (endTime == null) {
                    endTime = DateUtils.getDate(task.getStr("CALENDAR_ENDTIME"), DateUtils.DAFAULT_DATE_FORMAT);
                }
                if ("1".equals(task.getStr("CALENDAR_YESORNO_CODE"))) {
                    startTime = DateUtils.clearTime(startTime);
                    endTime.setHours(23);
                    endTime.setMinutes(59);
                    endTime.setSeconds(59);
                }
                if (!nowDate.after(endTime)) {
                    startTime.setMinutes(startTime.getMinutes() - remind);
                    if (nowDate.after(startTime)) {
                        taskNode.setIcon("JE_CORE_NZPLANTX16");
                    }
                }
            }
            taskNode.setBean(task.getValues());
            taskNode.setLeaf(true);
            lists.add(taskNode);
        }
        root.setChildren(lists);
        return root;
    }

    @XxlJob("calendarServiceTask")
    @Override
    public void tasks() {
        logger.info("calendarServiceTask.executeJob task start: " + DateUtils.formatDateTime(new Date()));
        StopWatch watch = new StopWatch();
        watch.start();

        List<DynaBean> dynaBeanList = metaService.select("JE_SYS_CALENDAR_PUSH", ConditionsWrapper.builder().likeRight("PUSH_TIME", DateUtil.now().substring(0, DateUtil.now().length() - 3)));
        taskExecutor.execute(() -> {
            Message message = null;
            for (DynaBean dynaBean : dynaBeanList) {
                try {

                    String id = dynaBean.getStr("JE_SYS_CALENDAR_ID");
                    if (StringUtil.isEmpty(id)) {
                        continue;
                    }
                    DynaBean bean = metaService.selectOne("JE_SYS_CALENDAR", ConditionsWrapper.builder().eq("JE_SYS_CALENDAR_ID", id));
                    //推送
                    String types = bean.getStr("CALENDAR_MESSAGETYPE_CODE");
                    if (StringUtil.isEmpty(types)) {
                        continue;
                    }
                    message = new Message();
                    message.setUserId(bean.getStr("SY_CREATEUSERID"));
                    message.setTitle(bean.getStr("CALENDAR_TITLE"));
                    message.setContent(bean.getStr("CALENDAR_NOTES"));
                    message.setButtonAction(bean.getStr("CALENDAR_URL", ""));
                    message.setBean(bean.getValues());
                    message.setWebPushTypeEnum(WebPushTypeEnum.MSG);//首页消息通知
                    List<Push> pushTypes = new ArrayList<>();
                    String[] typeList = types.split(",");
                    for (String type : typeList) {
                        if ("WEB".equals(type)) {
                            Notice notice = new Notice();
                            notice.setTitle("日程任务提醒");
                            notice.setContent("请关注【" + bean.getStr("CALENDAR_STARTTIME") + "，" + bean.getStr("CALENDAR_TITLE") + "】日程任务！");
                            //右下角推送
                            socketPushMessageRpcService.sendNoticeOpenFuncFormMsgToUser(bean.getStr("SY_CREATEUSERID"), null, "日程提醒", notice, bean.getPkValue());
                            //右上角通知
                            portalRpcService.insertOrUpdateSign(bean.getStr("SY_CREATEUSERID"), bean.getStr("SY_CREATEORGID"), WebPushTypeEnum.MSG, "insert");
                            //右上角通知 监听
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("code", "RC");
                            jsonObject.put("type", "MSG_RC");
                            jsonObject.put("data", dynaBean);
                            PushSystemMessage pushSystemMessage = new PushSystemMessage("MSG", String.valueOf(jsonObject));
                            pushSystemMessage.setTargetUserIds(Lists.newArrayList(bean.getStr("SY_CREATEUSERID")));
                            pushSystemMessage.setSourceUserId("系统");
                            socketPushMessageRpcService.sendMessage(pushSystemMessage);
                            //通知列表添加
                            NoticeMsg noticeMsg = new NoticeMsg(bean.getStr("SY_CREATEUSERID"), bean.getStr("SY_CREATEUSERNAME"), bean.getStr("SY_CREATEORGID"), bean.getStr("SY_CREATEORGNAME"),
                                    "请关注【" + bean.getStr("CALENDAR_STARTTIME") + "，" + bean.getStr("CALENDAR_TITLE") + "】日程任务！", "日程任务提醒", "RC", "日程");
                            portalRpcService.insertNoticeMsg(noticeMsg);

                            continue;
                        }
                        if (Push.check(type) != null) {
                            pushTypes.add(Push.check(type));
                        }

                    }
                    platformGeneralPushRpcService.sendPlatformMessage(pushTypes, message);
                    metaService.delete("JE_SYS_CALENDAR_PUSH", ConditionsWrapper.builder().eq("JE_SYS_CALENDAR_PUSH_ID", dynaBean.getPkValue()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            watch.stop();
            logger.info("calendarServiceTask.executeJob task end: " + DateUtils.formatDateTime(new Date()));
            logger.info("calendarServiceTask.executeJob task 耗时: " + watch.getTotalTimeSeconds() + " 秒");
        });
    }

}
